import { useEffect, useState } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
} from "react-native";
import { getStorageData, setStorageData } from "utils";
import toast from "utils/toast";
import translate from "utils/translate";
type FormData = {
  goodsName?: string;
  price?: string;
  unit?: string;
  id?: string;
};
type FormKeys = keyof FormData;
export default ({
  navigation,
  route: { params },
}: RootStackScreenProps<"addGoods">) => {
  const [form, setForm] = useState<FormData>({
    goodsName: "",
    price: "",
    unit: "",
  });
  useEffect(() => {
    const {
      index,
      createTime,
      unit = translate("main.weightUnit"),
      id,
      ...rest
    } = params;
    setForm(() => {
      return {
        ...rest,
        id: index?.toString(),
        unit,
      };
    });
  }, []);
  const handleSave = async () => {
    for (let p of List) {
      if (
        p.maxLength &&
        (form[p.prop as FormKeys]?.replaceAll(/[\u4e00-\u9fa5]/g, "aa")
          ?.length ?? 0) > (p.maxLength ?? 0)
      ) {
        return toast(translate("main.tooLong"));
      }
    }
    if (form.unit && form.price && form.goodsName) {
      // if (form.goodsName.replaceAll(/[\u4e00-\u9fa5]/g, "aa").length > 10) {
      //   return toast("输入的商品名称过长");
      // }
      const StorageData = await getStorageData("classList");
      const classList = StorageData ? JSON.parse(StorageData) : [];
      const index = classList.findIndex((item: { id: number }) => {
        return item.id === params.id;
      });

      if (params.index) {
        const { goodsList, ...rest } = classList[index];
        goodsList.splice(params.index - 1, 1, form);
        classList.splice(index, 1, {
          ...rest,
          goodsList,
        });
      } else {
        const { goodsList = [], ...rest } = classList[index];
        goodsList.push(form);
        classList.splice(index, 1, {
          ...rest,
          goodsList,
        });
      }
      setStorageData("classList", JSON.stringify(classList)).then(() => {
        navigation.goBack();
      });
    } else {
      toast(translate("main.toCmplete"));
    }
  };
  const handleChange = (value: string, key: FormKeys) => {
    setForm((prevForm) => ({
      ...prevForm,
      [key]: value,
    }));
  };
  const List = [
    {
      label: translate("main.id"),
      prop: "id",
    },
    {
      label: translate("class.goodsName"),
      prop: "goodsName",
      placeholder: translate("class.tipGoodsName"),
      maxLength: 10,
      multiline: true,
      numberOfLines: 2,
    },
    {
      label: translate("class.price"),
      prop: "price",
      placeholder: translate("class.priceTip"),
      maxLength: 6,
      keyboardType: "numeric",
    },
    {
      label: translate("class.unit"),
      prop: "unit",
      placeholder: translate("class.unitTip"),
      maxLength: 4,
    },
  ];
  return (
    <View
      style={{
        flex: 1,
        backgroundColor: "#fff",
      }}
    >
      <ScrollView
        style={{
          flex: 1,
          marginTop: 40,
        }}
        contentContainerStyle={{ alignItems: "center" }}
      >
        {List.map((item) => {
          return (
            <View
              key={item.label}
              style={{
                flexDirection: "row",
                alignItems: "center",
                marginBottom: 20,
                width: "90%",
              }}
            >
              <Text
                style={{
                  width: 60,
                }}
              >
                {item.label}
              </Text>

              <View
                style={{
                  flexDirection: "row",
                  alignItems: "center",
                  borderWidth: 1,
                  borderRadius: 8,
                  marginLeft: 10,
                  marginRight: 10,
                  borderColor: "#ccc",
                  padding: 8,
                  flex: 1,
                  width: 200,
                  justifyContent: "space-between",
                }}
              >
                <TextInput
                  onChangeText={(value) => {
                    handleChange(value, item.prop as FormKeys);
                  }}
                  defaultValue={form[item.prop as FormKeys]}
                  style={{
                    flex: 5,
                  }}
                  //@ts-ignore
                  keyboardType={item.keyboardType}
                  multiline={item.multiline}
                  numberOfLines={item.numberOfLines}
                  placeholder={item.placeholder}
                ></TextInput>
                {item.prop !== "id" && (
                  <Text style={{ flex: 1, minWidth: 10, marginLeft: 5 }}>
                    {form[item.prop as FormKeys]?.replaceAll(
                      /[\u4e00-\u9fa5]/g,
                      "aa"
                    )?.length ?? 0}
                    /{item.maxLength}
                  </Text>
                )}
              </View>
            </View>
          );
        })}
        <TouchableOpacity style={styles.button} onPress={handleSave}>
          <Text
            style={{
              textAlign: "center",
              color: "#fff",
            }}
          >
            {translate("main.save")}
          </Text>
        </TouchableOpacity>
        {params.index && (
          <TouchableOpacity
            style={{
              ...styles.button,
              backgroundColor: "#e54d42",
            }}
            onPress={async () => {
              const StorageData = await getStorageData("classList");
              const classList = StorageData ? JSON.parse(StorageData) : [];
              const index = classList.findIndex((item: { id: number }) => {
                return item.id === params.id;
              });
              const { goodsList, ...rest } = classList[index];
              goodsList.splice((params?.index ?? 0) - 1, 1);
              classList.splice(index, 1, {
                ...rest,
                goodsList,
              });
              setStorageData("classList", JSON.stringify(classList)).then(
                () => {
                  navigation.goBack();
                }
              );
            }}
          >
            <Text
              style={{
                textAlign: "center",
                color: "#fff",
              }}
            >
              {translate("main.delete")}
            </Text>
          </TouchableOpacity>
        )}
      </ScrollView>
    </View>
  );
};
const styles = StyleSheet.create({
  button: {
    backgroundColor: "#0A59F7",
    width: "60%",
    height: 50,
    marginBottom: 30,
    borderRadius: 16,
    alignItems: "center",
    justifyContent: "center",
    alignSelf: "center",
  },
});
